package com.example.girls.adapter

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.example.girls.R
import com.example.girls.data.PhotoItem
import com.example.girls.viewModels.MyViewModel
import com.example.girls.viewModels.NetWorkStatus
import kotlinx.android.synthetic.main.girls_cell.view.*
import kotlinx.android.synthetic.main.girls_cell_footer.view.*


const val PHOTO_INDEX = "photo_index"
val diffCallback = object : DiffUtil.ItemCallback<PhotoItem>() {
    override fun areItemsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
        return oldItem === newItem
    }

    override fun areContentsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
        return oldItem._id == newItem._id
    }

}

class GirlAdapter(private val myViewModel: MyViewModel) :
    ListAdapter<PhotoItem, RecyclerView.ViewHolder>(diffCallback) {
    companion object {
        const val FOOTER_VIEW_TYPE = 0
        const val GIRLS_VIEW_TYPE = 1
    }

    private var networkStatus: NetWorkStatus? = null

    fun updateNetWorkStatus(networkStatus: NetWorkStatus?) {
        this.networkStatus = networkStatus
    }

    override fun getItemCount(): Int {
        return super.getItemCount() + 1
    }

    override fun getItemViewType(position: Int): Int {
        return if (itemCount - 1 == position) FOOTER_VIEW_TYPE else GIRLS_VIEW_TYPE
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
        when (viewType) {
            FOOTER_VIEW_TYPE -> {
                FooterViewHolder.newInstance(parent).also {
                    it.itemView.setOnClickListener {
                        myViewModel.fetchData()
                    }
                }
            }
            else -> {
                GirlsViewHolder.newInstance(parent).also { holder ->
                    holder.itemView.setOnClickListener {
                        Bundle().apply {
                            myViewModel.currentPosition = holder.adapterPosition
                            holder.itemView.findNavController()
                                .navigate(R.id.action_galleryFragment_to_photoFragment)
                        }

                    }
                }
            }
        }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder.itemViewType == FOOTER_VIEW_TYPE) {
            (holder as FooterViewHolder).bindWithNetWorkStatus(networkStatus)
        } else {
            val photoItem = getItem(position) ?: return
            (holder as GirlsViewHolder).bindWithPhoto(getItem(position))
        }
    }
}

class GirlsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    companion object {
        fun newInstance(parent: ViewGroup): GirlsViewHolder {
            LayoutInflater.from(parent.context).inflate(R.layout.girls_cell, parent, false).also {
                return GirlsViewHolder(it)
            }
        }
    }

    fun bindWithPhoto(photoItem: PhotoItem) {
        itemView.apply {
            shimmerLayoutCell.apply {
                setShimmerColor(0x55FFFFFF)
                setShimmerAngle(0)
                startShimmerAnimation()
            }

            Glide.with(this)
                .load(photoItem.url)
                .placeholder(R.color.shimmer_color)
                .error(R.drawable.ic_jiazaishibai)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        shimmerLayoutCell.stopShimmerAnimation()
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable?,
                        model: Any?,
                        target: Target<Drawable>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false.also {
                            shimmerLayoutCell.stopShimmerAnimation()
                        }
                    }

                })
                .into(imageView)
        }
    }
}

class FooterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    companion object {
        fun newInstance(parent: ViewGroup): FooterViewHolder {
            LayoutInflater.from(parent.context).inflate(R.layout.girls_cell_footer, parent, false)
                .also {
                    (it.layoutParams as StaggeredGridLayoutManager.LayoutParams).isFullSpan = true
                    return FooterViewHolder(it)
                }
        }
    }

    fun bindWithNetWorkStatus(netWorkStatus: NetWorkStatus?) {
        itemView.apply {
            when (netWorkStatus) {
                NetWorkStatus.ERROR -> {
                    progressBarFooter.visibility = View.GONE
                    textViewFooter.text = "网络故障，点击重试"
                    isClickable = true
                }
                NetWorkStatus.COMPLETE -> {
                    progressBarFooter.visibility = View.GONE
                    textViewFooter.text = "已全部加载完毕"
                    isClickable = false
                }
                else -> {
                    progressBarFooter.visibility = View.VISIBLE
                    textViewFooter.text = "正在加载中....."
                    isClickable = false
                }
            }
        }
    }
}